<?php

namespace Controller\Account;

use Silex\Application;
use Silex\ControllerProviderInterface;
use Silex\ControllerCollection;

class MapCSP implements ControllerProviderInterface {
    public function connect(Application $app) {
        $controllers = $app ['controllers_factory'];
        $controllers->match ( '/{gpsAcct}', function (Application $app, $gpsAcct) {
            
            $qb = $app ['em']->createQueryBuilder ();
            
            $today = date ( 'Y-m-d', strtotime('today') );
            
            $qb->select ( array (
                            'p',
                            'r' 
            ) )->from ( '\Entity\Purchase', 'p' )->leftJoin ( 'p.records', 'r' )->where ( 'p.gpsAcct = :gpsAcct' )->andWhere ( 'r.date >= :start' )->andWhere ( 'r.date <= :end' )->setParameter ( 'gpsAcct', $gpsAcct )->setParameter ( 'start', "$today 00:00:00" )->setParameter ( 'end', "$today 23:59:59" );
            
            $query = $qb->getQuery ();
            $results = $query->getResult ();
            
            // Render
            if (count ( $results ) > 0) {
                return $app ['twig']->render ( "account/map.twig", array (
                                'data' => $results [0] 
                ) );
            } else {
                return $app ['twig']->render ( "install/404.twig", array () );
            }
        }, 'GET|POST' );
        
        return $controllers;
    }
}